"""
数据类
@dataclass 帮我们完成init str repr eq 等方法
init=True: 初始化 是否要提供
repr=True: 是否加载repr方法上打印

"""
import operator
from dataclasses import dataclass, field


# frozen=True 不可变对象 定制化属性就不能用了
@dataclass(frozen=True)
class Student:
    name: str
    age: int
    score: int = field(default=1, init=True, repr=True)

    # # 定制化属性
    # def __post_init__(self):
    #     self.score = self.score if self.score < 100 else 20


@dataclass()
class Student2:
    name: str
    age: int
    score: int = field(default=1, init=True, repr=True)

    # 定制化属性
    def __post_init__(self):
        self.score = self.score if self.score < 100 else 20


# 排序，默认按照第一个定义的属性，升序排序
@dataclass(order=True)
class Student2:
    # # 定义一个属性用于排序，不用传
    # sorted_index: int = field(init=False, repr=False)

    name: str
    age: int
    score: int = field(default=1, init=True, repr=True)

    # 定制化属性
    def __post_init__(self):
        self.score = self.score if self.score < 100 else 20
        self.sorted_index = self.age  # 把age赋值给sorted_index  如果前面没有定义，相当于新增了一个属性


s1 = Student2("Hello", 19)
s2 = Student2("Abc", 20)
print(s1 == s2)  # True
print(s1.__repr__())
print(s1.sorted_index)

students = [s1, s2]


# [Student2(name='Abc', age=20, score=1), Student2(name='Hello', age=19, score=1)]
print(sorted(students))

# 另一种排序写法，指定key
students.sort(key=operator.attrgetter("name"))  # 原地排序，改变了students
# # [Student2(name='Abc', age=20, score=1), Student2(name='Hello', age=19, score=1)]
print(students)

# [Student2(name='Hello', age=19, score=1), Student2(name='Abc', age=20, score=1)]
students.sort(key=operator.attrgetter("age"))
print(students)


